package com.wmlt.util;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class JdbcUtil {
    private static String url;
    private static String user;
    private static String password;
    private static String driver;
    private static  ThreadLocal<Connection>  threadLocal=new ThreadLocal<>();//当前线程池用来存放连接
    static {
        // 读取资源文件，获取值
        try {
            // 1.Properties集合类
            Properties properties = new Properties();
            // 2.加载文件
            InputStream is = JdbcUtil.class.getClassLoader().getResourceAsStream("jdbc.properties");
            properties.load(is);
            // 3.读取数据，赋值
            url = properties.getProperty("url");
            user = properties.getProperty("user");
            password = properties.getProperty("password");
            driver = properties.getProperty("driver");
            // 4.注册驱动
            Class.forName(driver);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }


    /**
     * @description 关闭连接
     * @param:
     * @return:
     * @author liyuxiang
     * @date: 2021/4/12 1:57 下午
     */
    public static Connection getConnection() {
        Connection connection=null;
        try {
            Class.forName(driver);
            if (connection==null){
                //
                connection= threadLocal.get();
                if(connection==null){
                    connection= DriverManager.getConnection(url,user,password);
                    threadLocal.set(connection);
                }
            }else{
                return connection;
            }
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
        return connection;

    }


    /**
     * @description: 关闭连接
     * @param:
     * @return:
     * @author liyuxiang
     * @date: 2021/4/12 1:57 下午
     */
    public static void close(ResultSet res, PreparedStatement prea, Connection connection) {
        try {
            if (res != null) {
                res.close();
            }
            if (prea != null) {
                prea.close();
            }
            if (connection != null) {
                connection.close();
                threadLocal.remove();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}